<?php

namespace app\jun\controller;

use app\erp\model\Attrdb;
use app\erp\model\AttrValuedb;
use app\erp\model\BrandApidb;
use app\erp\model\Branddb;
use app\erp\model\Cartdb;
use app\erp\model\Categorydb;
use app\erp\model\ComOrderdb;
use app\erp\model\Goodsdb;
use app\erp\model\JunCitydb;
use app\erp\model\Memberdb;
use app\erp\model\Orderdb;
use app\erp\model\OrderLogdb;
use app\erp\model\OrderSubmitLogdb;
use app\erp\model\Returneddb;
use app\erp\model\SalePricedb;
use app\erp\model\Shoppingdb;
use app\erp\model\Sitedb;
use app\erp\model\Uploaddb;

class Ecservice extends Base
{
    protected $appkey = 'jun_admin';
    protected $appsecret = '4k3xNmKO';
    protected $api_url = 'https://zc.plap.mil.cn/api/';
    protected $apiKey = 'zXAOSQxT';
    protected $apiSecret = '7x0DzpqUlS';

    public function _initialize()
    {
        parent::_initialize();
        if (!isset ($this->request ['appKey']) || $this->request ['appKey'] != $this->appkey) {
            $this->errorReturn('appKey错误');
        }
    }

    public function getAccessToken()
    {
        if (!isset ($this->request ['appSecret']) || $this->request ['appSecret'] != $this->appsecret) {
            $this->errorReturn('appSecret错误');
        }
        $return ['accessToken'] = md5($this->appkey . $this->appsecret);
        $this->successReturn($return);
    }

    // 品目商品
    public function getProductPool()
    {
        $post_json ['api_option'] = $this->request ['categoryId'];
        $data = $this->sendInfo('getGoodsSku', $post_json);
        $return ['sku'] = $data ['data'];
        $this->successReturn($return);
    }

    // 获取token
    public function getAccessTokenApi()
    {
        $sitedb = new Sitedb();
        $get_site = $sitedb->ajaxFind(SITE_ID);
        if ($get_site ['access_token']) {
            if (time() >= $get_site ['expires_stop_time'] + 3600) {
                $post_json ['appKey'] = $this->apiKey;
                $post_json ['appSecret'] = $this->apiSecret;
                $result = $this->sendInfo('ecservice/getAccessToken', $post_json);
                $token = $result ['accessToken'];
                $sitedb->save([
                    'access_token' => $token,
                    'expires_stop_time' => time()
                ], [
                    'site_id' => SITE_ID
                ]);
            } else {
                $token = $get_site ['access_token'];
            }
        } else {
            $post_json ['appKey'] = $this->apiKey;
            $post_json ['appSecret'] = $this->apiSecret;
            $result = $this->sendInfo('ecservice/getAccessToken', $post_json);
            $token = $result ['accessToken'];
            $sitedb->save([
                'access_token' => $token,
                'expires_stop_time' => time()
            ], [
                'site_id' => SITE_ID
            ]);
        }

        return $token;
    }

    protected function sendInfoApi($string_uri, $post)
    {
        if ($string_uri != 'ecservice/getAccessToken') {
            $post ['accessToken'] = $this->getAccessTokenApi();
            $post ['appKey'] = $this->apiKey;
        }
        $json_data = json_encode($post);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->api_url . $string_uri);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Content-type: application/json;charset='utf-8'"
        ));
        $result = curl_exec($ch);
        curl_close($ch);
        $return_json = json_decode($result, true);

        if (!isset ($return_json ['isSuccess']) || $return_json ['isSuccess'] != 1) {
            /*
             * print_r ( '提交参数:' );
             * print_r ( $json_data );
             * print_r ( '提交网址：' );
             * print_r ( $this->api_url . $string_uri );
             * print_r ( chr ( 13 ) );
             * print_r ( '返回信息：' );
             * print_r ( $return_json );
             */
            return $return_json;
        } else {
            return $return_json;
        }
    }

    // 商品详情
    public function getProductDetail()
    {
        /*$post_json ['goods_sku'] = $this->request ['sku'];
        $post_json ['no_more_price'] = 'yes';
        $post_json ['member_id'] = $this->member_id;
        $get_goods = $this->sendInfo('goodsOnlyDetail', $post_json);*/
        $goodsdb = new Goodsdb();
        $data = $goodsdb->where('goods_sku', $this->request['sku'])->find();
        $categorydb = new Categorydb();
        $get_category = $categorydb->where('category_sign', $data['category_sign3'])->field('api_option')->find();
        $post_json_api['categoryId'] = $get_category['api_option'];
        $get_attr_api = $this->sendInfoApi('ecservice/getCidParams', $post_json_api);
        $return ['sku'] = $data ['goods_sku'];
        $return ['weight'] = $data ['weight'];
        $uploaddb = new Uploaddb();
        if ($data['goods_picture']) {
            $upload_id = $data['goods_picture'];
        } else {
            $ts = explode(',', $data['goods_pictures']);
            $upload_id = $ts[0];
        }
        $get_upload = $uploaddb->getFind($upload_id);
        $return ['image'] = $get_upload ['save_path'];
        $return ['state'] = $data ['sale_state'] ? 1 : 2;
        $branddb = new Branddb();
        $get_brand = $branddb->where('brand_sign', $data['brand_sign'])->field('brand_name')->find();
        $return ['brand'] = $get_brand ['brand_name'];
        $brandapidb = new BrandApidb();
        $get_brand_api = $brandapidb->where('brand_sign', $data['brand_sign'])->field('option')->find();
        if ($get_brand_api) {
            $return ['brandid'] = $get_brand_api['option'];
        }
        $return ['model'] = $data ['goods_model'];
        $return ['name'] = $data ['goods_name'];
        $return ['productArea'] = $data ['product_area'];
        $return ['upc'] = $data ['code_69'];
        $return ['saleUnit'] = $data ['goods_unit'];
        $return ['category'] = $get_category['api_option'];
        $return ['introduction'] = $data ['goods_content'];
        $return ['ecurl'] = $data['ziying_url'];
        $return ['producttype'] = $data['is_zhongdian'];
        $salePricedb = new SalePricedb();
        $get_price = $salePricedb->where('goods_sku', $data['goods_sku'])->field('market_price,sale_price,api_price')->find();
        $return ['marketPrice'] = $get_price ['sale_price'];
        $return ['minOrderCount'] = 1;
        $return ['saleSpecifications'] = $data['sale_specifications'];
        $return ['standardUnit'] = $data['standard_unit'];
        $attr = array();
        $get_attr_api = $get_attr_api['paramList'];
        // 分类属性值
        $attrValuedb = new AttrValuedb ();
        $val ['attr_value'] = $attrValuedb->ajaxSelect($data ['goods_sku']);
        // 分类属性
        $attrdb = new Attrdb ();
        $attrdb->param ['category_sign'] = $data ['category_sign3'];
        $category_attr = $attrdb->ajaxList();
        $attr_arr = array();
        foreach ($category_attr as $k => $v) {
            $attr_arr [$k] ['group_name'] = $v ['group_name'];
            $attr_arr [$k] ['attr_name'] = $v ['attr_name'];
            if (isset ($val ['attr_value'] [$v ['attr_sign']])) {
                $attr_arr [$k] ['attr_value'] = $val ['attr_value'] [$v ['attr_sign']];
            } else {
                $attr_arr [$k] ['attr_value'] = '';
            }
        }
        foreach ($get_attr_api as $k => $v) {
            //if ($v['ismust'] == 1) {
            foreach ($attr_arr as $key => $val) {
                if ($val['attr_name'] == $v['param_name']) {
                    if ($v['input_type'] == 1) {
                        foreach ($v['paramsvalues'] as $k1 => $v1) {
                            if ($v1['value_text'] == $val['attr_value']) {
                                $attr[$v['param_id']] = $v1['value_id'];
                            }
                        }
                    } elseif ($v['input_type'] == 2) {
                        $temp_v = explode(',', $val['attr_value']);
                        $attr[$v['param_id']] = array();
                        foreach ($v['paramsvalues'] as $k1 => $v1) {
                            for ($j = 0; $j < count($temp_v); $j++) {
                                if (isset($v1['value_text']) && $v1['value_text'] == $temp_v[$j]) {
                                    array_push($attr[$v['param_id']], $v1['value_id']);
                                }
                            }
                        }
                        //$attr[$v['param_id']] = '';
                    } else {
                        $attr[$v['param_id']] = $val['attr_value'];
                    }
                }
            }
            //}
        }
        /*
		foreach ( $data ['goods_attr'] as $key => $val ) {
		    if($val['attr_value'] != '') {
                $attr [$val ['attr_name']] = $val ['attr_value'];
            }
		}
        */
        $new_attr = [];
        foreach ($attr as $key => $val) {
            if ($val) {
                $new_attr[$key] = $val;
            }
        }
        $return ['param'] = $new_attr;
        $return ['isProtected'] = $data ['is_energy'] ? 1 : 0;
        if ($return ['isProtected']) {
            $return ['jieNengDate'] = $data ['energy_cert_indate'];
            $return ['huanBaoDate'] = $data ['environment_protect_cert_indate'];
            $return ['jieNengCertificate'] = $data ['energy_cert_no'];
            $return ['jieNengCertificateUrl'] = $data ['energy_cert_image'];
            $return ['jieNengAuthorites'] = '';
            $return ['huanBaoCertificate'] = $data ['environment_protect_cert_no'];
            $return ['huanBaoCertificateUrl'] = $data ['environment_protect_cert_image'];
            $return ['huanBaoAuthorites'] = '';
        }
        $this->successReturn($return);
    }

    // 商品图片
    public function getProductImage()
    {
        $post_json ['goods_sku'] = $this->request ['sku'];
        $data = $this->sendInfo('goodsPicture', $post_json);
        $return ['result'] = array();
        foreach ($data ['data'] as $key => $val) {
            $temp ['skuId'] = $val ['goods_sku'];
            $temp ['urls'] = array();
            $i = 0;
            foreach ($val ['goods_pictures'] as $k => $v) {
                if (isset($v ['save_path'])) {
                    $t ['path'] = $v ['save_path'];
                    $t ['primary'] = $i == 0 ? 1 : 0;
                    $i++;
                    array_push($temp ['urls'], $t);
                }
            }
            array_push($return ['result'], $temp);
        }
        $this->successReturn($return);
    }

    // 销售状态
    public function getProductOnShelvesInfo()
    {
        $post_json ['goods_sku'] = $this->request ['sku'];
        $data = $this->sendInfo('goodsPicture', $post_json);
        $return ['onShelvesList'] = array();
        foreach ($data ['data'] as $key => $val) {
            $temp ['skuId'] = $val ['goods_sku'];
            $temp ['listState'] = $val ['sale_state'] == 1 ? 1 : 0;
            array_push($return ['onShelvesList'], $temp);
        }
        $this->successReturn($return);
    }

    // 库存
    public function getProductInventory()
    {
        $post_json ['goods_sku'] = $this->request ['sku'];
        $post_json ['no_more_price'] = 'yes';
        $post_json ['member_id'] = $this->member_id;
        $data = $this->sendInfo('goodsOnlyDetail', $post_json);
        if (!$data) {
            $this->errorReturn('未找到数据');
        }
        $result ['skuId'] = $this->request ['sku'];
        if ($data ['count'] == 0) {
            $result ['state'] = '01';
        } else {
            if ($data ['data'] ['view_stock'] < $this->request ['num']) {
                $result ['state'] = '03';
            } else {
                $result ['state'] = '00';
            }
        }
        $result ['returnMsg'] = $this->request ['provinceId'];
        $this->successReturn($result);
    }

    // 预占订单
    public function createOrder()
    {
        $order_data = array();
        // 收货地址
        $api = new Api ();
        $junCitydb = new JunCitydb();
        $get_p = $junCitydb->where('citycode', $this->request ['provinceId'])->find();
        $get_c = $junCitydb->where('citycode', $this->request ['cityId'])->find();
        $get_a = $junCitydb->where('citycode', $this->request ['countyId'])->find();
        /*$get_p = $api->getAddressInfo($this->request ['provinceId']);
        $get_c = $api->getAddressInfo($this->request ['cityId']);
        $get_a = $api->getAddressInfo($this->request ['countyId']);*/
        $shoppingdb = new Shoppingdb ();
        $shoppingdb->param ['province'] = $get_p['cityname'];
        $shoppingdb->param ['city'] = $get_c['cityname'];
        $shoppingdb->param ['area'] = $get_a['cityname'];
        $shoppingdb->param ['street'] = $this->request ['address'];
        $shoppingdb->param ['contacts'] = $this->request ['name'] ?: '无';
        $shoppingdb->param ['phone'] = $this->request ['mobile'];
        $shoppingdb->param ['email'] = $this->request ['email'];
        $shoppingdb->param ['is_default'] = 1;
        $shoppingdb->param ['member_id'] = $this->member_id;
        $shoppingdb->ajaxSave();
        $order_data ['shopping_id'] = intval($shoppingdb->last_id);
        // 购物车信息
        $cart_info = $this->request ['sku'];
        $cart_arr = array();
        $all_money = 0;
        foreach ($cart_info as $key => $val) {
            $goodsdb = new Goodsdb();
            $chk_goods = $goodsdb->where('goods_sku', $val['skuId'])->find();
            if ($chk_goods) {
                $temp ['goods_sku'] = $val ['skuId'];
            } else {
                $get_goods = $goodsdb->where('goods_id', $val['skuId'])->find();
                if ($get_goods) {
                    $temp ['goods_sku'] = $get_goods['goods_sku'];
                } else {
                    $temp ['goods_sku'] = $val ['skuId'];
                }
            }
            $salePricedb = new SalePricedb();
            $get_price = $salePricedb->where('goods_sku', $temp['goods_sku'])->find();
            $get_price->save(['view_stock' => $get_price['view_stock'] - $val['num']]);
            /*if(is_numeric($val['skuId'])) {

                $get_goods = $goodsdb->find($val['skuId']);
                if ($get_goods) {
                    $temp ['goods_sku'] = $get_goods['goods_sku'];
                }
            }*/
            $temp ['sale_price'] = $val ['price'];
            $temp ['goods_attr_view'] = '';
            $temp ['goods_attr'] = '';
            $temp ['num'] = $val ['num'];
            $temp ['member_id'] = $this->member_id;
            $temp ['sale_attr'] = '商品价格';
            $temp ['sale_attr_html'] = '';
            array_push($cart_arr, $temp);
        }
        $order_data ['select_goods_info'] = $cart_arr;
        // 发票信息
        if (isset ($this->request ['invoiceState']) == 1) {
            $order_data ['is_invoice'] = $this->request ['invoiceState'] == 1 ? 2 : 1;
            $order_data ['invoice_type'] = $this->request ['invoiceType'] == 1 ? 3 : 1;
            $order_data ['invoice_title'] = $this->request ['companyName'];
            //  $order_data ['invoice_duty'] = $this->request ['invoiceTaxNo'];
            $order_data ['invoice_addr'] = ' ';
            $order_data ['invoice_tel'] = ' ';
            $order_data ['invoice_bank'] = ' ';
            $order_data ['invoice_account'] = ' ';
            $order_data ['invoice_content'] = $this->request ['invoiceContent'];
            $order_data ['invoice_money'] = $this->request ['amount'] * 100;
        }
        $order_data ['member_id'] = $this->member_id;
        // 订单信息
        $order_data ['order_money'] = $this->request ['amount'] * 100;
        $order_data ['order_member_id'] = $this->member_id;
        $order_data ['songda_time'] = date('Y-m-d', strtotime('+3 day'));
        $order_data ['out_order_no'] = $this->request ['tradeNo'];
        $order_data ['yonghu_beizhu'] = $this->request ['remark'];
        $order_data ['hezuodanwei'] = '泰龙吉';
        $order_data ['apply_state'] = '1';
        $order_data ['jun_order_type'] = $this->request ['submitState'] == 0 ? 1 : 2;
        $order_data ['order_state'] = $this->request ['submitState'] == 0 ? 1 : 2;
        $order_data ['api_param'] = json_encode($this->request);
        $order_data ['phone'] = $this->request['mobile'] ?: '';
        $orderdb = new Orderdb ();
        $orderdb->param = $order_data;
        $orderdb->addOrder();

        // 发票结束
        $return ['orderId'] = $orderdb->last_order_no;
        $return ['sku'] = $this->request ['sku'];
        $return ['arriveData'] = $order_data ['songda_time'];
        $return ['amount'] = $this->request ['amount'];
        $return ['freight'] = $this->request ['freight'];

        $save_com['order_no'] = $this->request ['tradeNo'];
        $comOrderdb = new ComOrderdb();
        $comOrderdb->save($save_com);
        $this->successReturn($return);
    }

    // 预占订单新版
    public function createOrderNew()
    {
        $order_data = array();
        // 收货地址
        $api = new Api ();
        $junCitydb = new JunCitydb();
        $get_p = $junCitydb->where('citycode', $this->request ['provinceId'])->find();
        $get_c = $junCitydb->where('citycode', $this->request ['cityId'])->find();
        $get_a = $junCitydb->where('citycode', $this->request ['countyId'])->find();
        /*$get_p = $api->getAddressInfo($this->request ['provinceId']);
        $get_c = $api->getAddressInfo($this->request ['cityId']);
        $get_a = $api->getAddressInfo($this->request ['countyId']);*/

        // 购物车信息
        $cart_info = $this->request ['sku'];
        $cart_arr = array();
        $all_money = 0;
        $order_submit_log = [];
        $chk_flag = 1;
        $chk_msg = '';
        foreach ($cart_info as $key => $val) {
            $goodsdb = new Goodsdb();
            $log_temp = array();
            //$goods_flag = 1;
            $log_temp ['goods_flag'] = 1;
            $log_temp ['flag_msg'] = '成功';
            $chk_goods = $goodsdb->append(['zuidijia'])->where('goods_sku', $val['skuId'])->find();
            if ($chk_goods) {
                $temp ['goods_sku'] = $val ['skuId'];
                $log_temp['zhenshi'] = $chk_goods['zhenshi'];
                $log_temp['diqu'] = $chk_goods['diqu'];
                $log_temp['shengfen'] = $chk_goods['shengfen'];
                $log_temp['zuidi'] = $chk_goods['zuidijia'];
                $log_temp['cankaojia'] = $chk_goods['sale_price'];
            } else {
                $get_goods = $goodsdb->where('goods_id', $val['skuId'])->find();
                if ($get_goods) {
                    $temp ['goods_sku'] = $get_goods['goods_sku'];
                    $log_temp['zhenshi'] = $get_goods['zhenshi'];
                    $log_temp['diqu'] = $get_goods['diqu'];
                    $log_temp['shengfen'] = $get_goods['shengfen'];
                    $log_temp['zuidi'] = $chk_goods['zuidijia'];
                    $log_temp['cankaojia'] = $chk_goods['sale_price'];
                } else {
                    $temp ['goods_sku'] = $val ['skuId'];
                    $log_temp['zhenshi'] = 0;
                    $log_temp['diqu'] = '1';
                    $log_temp['shengfen'] = '';
                    $log_temp['zuidi'] = 0;
                    $log_temp['cankaojia'] = 0;
                }
            }
            // 开始校验 真实库存 地区
            if ($log_temp['zhenshi'] < $val ['num']) {
                $chk_flag = 0;
                $log_temp['goods_flag'] = 0;
                $log_temp['flag_msg'] = '库存不足';
                $chk_msg = $val['goods_name'] . '，商品库存：' . $val['num'] . '，库存不足';
                //$chk_msg = $val ['skuId'] . '库存不足;';
            }
            // 偏远地区校验
            $shengfen_arr = explode(',', $log_temp['shengfen']);
            if ($log_temp['diqu'] == '2' && !in_array($get_p['cityname'], $shengfen_arr)) {
                $chk_flag = 0;
                $log_temp['goods_flag'] = 0;
                $log_temp['flag_msg'] = '地区库存不足';
                $chk_msg = $val['goods_name'] . '，地区商品库存：' . $val['num'] . '，库存不足';
                //$chk_msg = $get_p['cityname'] . '地区库存不足;';
            }

            $log_temp['sku_id'] = $val['skuId'];
            $log_temp['num'] = $val['num'];
            $log_temp['price'] = $val['price'];
            $log_temp['province'] = $get_p['cityname'];
            $log_temp['out_order_no'] = $this->request ['tradeNo'];


            // 日志存数组
            array_push($order_submit_log, $log_temp);


            $temp ['sale_price'] = $val ['price'];
            $temp ['goods_attr_view'] = '';
            $temp ['goods_attr'] = '';
            $temp ['num'] = $val ['num'];
            $temp ['member_id'] = $this->member_id;
            $temp ['sale_attr'] = '商品价格';
            $temp ['sale_attr_html'] = '';
            array_push($cart_arr, $temp);
        }
        // 保存日志
        $orderSubmitDb = new OrderSubmitLogdb();
        $orderSubmitDb->saveAll($order_submit_log);
        // 如果校验没成功 返回失败
        if ($chk_flag == 0) {
            $return ['orderId'] = '';
            $return ['sku'] = $this->request ['sku'];
            $return ['arriveData'] = '';
            $return ['amount'] = $this->request ['amount'];
            $return ['freight'] = $this->request ['freight'];
            $return ['errorCode'] = 'ORDER007';
            $return ['returnMsg'] = '下单校验失败：' . $chk_msg;
            $this->junErrorReturn($return);
        }

        $shoppingdb = new Shoppingdb ();
        $shoppingdb->param ['province'] = $get_p['cityname'];
        $shoppingdb->param ['city'] = $get_c['cityname'];
        $shoppingdb->param ['area'] = $get_a['cityname'];
        $shoppingdb->param ['street'] = $this->request ['address'];
        $shoppingdb->param ['contacts'] = $this->request ['name'] ?: '无';
        $shoppingdb->param ['phone'] = $this->request ['mobile'];
        $shoppingdb->param ['email'] = $this->request ['email'];
        $shoppingdb->param ['is_default'] = 1;
        $shoppingdb->param ['member_id'] = $this->member_id;
        $shoppingdb->ajaxSave();
        $order_data ['shopping_id'] = intval($shoppingdb->last_id);

        $order_data ['select_goods_info'] = $cart_arr;
        // 发票信息
        if (isset ($this->request ['invoiceState']) == 1) {
            $order_data ['is_invoice'] = $this->request ['invoiceState'] == 1 ? 2 : 1;
            $order_data ['invoice_type'] = $this->request ['invoiceType'] == 1 ? 3 : 1;
            $order_data ['invoice_title'] = $this->request ['companyName'];
            //  $order_data ['invoice_duty'] = $this->request ['invoiceTaxNo'];
            $order_data ['invoice_addr'] = ' ';
            $order_data ['invoice_tel'] = ' ';
            $order_data ['invoice_bank'] = ' ';
            $order_data ['invoice_account'] = ' ';
            $order_data ['invoice_content'] = $this->request ['invoiceContent'];
            $order_data ['invoice_money'] = $this->request ['amount'] * 100;
        }
        $order_data ['member_id'] = $this->member_id;
        // 订单信息
        $order_data ['order_money'] = $this->request ['amount'] * 100;
        $order_data ['order_member_id'] = $this->member_id;
        $order_data ['songda_time'] = date('Y-m-d', strtotime('+3 day'));
        $order_data ['out_order_no'] = $this->request ['tradeNo'];
        $order_data ['yonghu_beizhu'] = $this->request ['remark'];
        $order_data ['hezuodanwei'] = '泰龙吉';
        $order_data ['apply_state'] = '1';
        $order_data ['jun_order_type'] = $this->request ['submitState'] == 0 ? 1 : 2;
        $order_data ['order_state'] = $this->request ['submitState'] == 0 ? 1 : 2;
        $order_data ['api_param'] = json_encode($this->request);
        $order_data ['phone'] = $this->request['mobile'] ?: '';
        $orderdb = new Orderdb ();
        $orderdb->param = $order_data;
        $orderdb->addOrder();

        // 发票结束
        $return ['orderId'] = $orderdb->last_order_no;
        $return ['sku'] = $this->request ['sku'];
        $return ['arriveData'] = $order_data ['songda_time'];
        $return ['amount'] = $this->request ['amount'];
        $return ['freight'] = $this->request ['freight'];

        $save_com['order_no'] = $this->request ['tradeNo'];
        $comOrderdb = new ComOrderdb();
        $comOrderdb->save($save_com);
        $this->successReturn($return);
    }

    // 确认预占订单
    public function ensureOrder()
    {
        $orderdb = new Orderdb ();
        $order_no = $this->request ['tradeNo'];
        $orderdb->param ['out_order_no'] = $order_no;
        $get_order = $orderdb->ajaxOrderNo();
        $orderdb = new Orderdb ();
        $orderdb->param ['event'] = 'edit_state';
        $orderdb->param ['order_no'] = $get_order ['order_no'];
        $orderdb->param ['post_data'] ['order_state'] = 2;
        $orderdb->editOrder();
        $return ['errorCode'] = 0;
        $this->successReturn($return);
    }

    // 订单退货
    public function backGoodsApply()
    {
        $orderdb = new Orderdb ();
        $order_no = $this->request ['tradeNo'];
        $orderdb->param ['out_order_no'] = $order_no;
        $get_order = $orderdb->ajaxOrderNo();
        $order_no = $get_order ['order_no'];
        $sku = $this->request ['sku'];
        foreach ($sku as $key => $val) {
            $post_json ['member_id'] = $this->member_id;
            $post_json ['returned_info'] ['order_no'] = $order_no;
            $post_json ['returned_info'] ['goods_sku'] = $val ['skuId'];
            $post_json ['returned_info'] ['returned_type'] = 1;
            $post_json ['returned_info'] ['returned_reason'] = $val ['backReason'];
            $post_json ['returned_info'] ['api_param'] = json_encode($this->request);
            $this->sendInfo('returnedGoodsThrid', $post_json);
        }
        $return ['tradeNo'] = $this->request ['tradeNo'];
        $return ['backNo'] = $order_no . '_back';
        $this->successReturn($return);
    }

    // 发票
    public function getInvoiceInfo()
    {
        $orderdb = new Orderdb ();
        $order_no = $this->request ['tradeNo'];
        $orderdb->param ['out_order_no'] = $order_no;
        $get_order = $orderdb->ajaxOrderNo();
        if (count($get_order) == 0) {
            $this->errorReturn('没有获取到信息');
        }
        $order_no = $get_order ['order_no'];
        $post_json ['order_no'] = $order_no;
        $data = $this->sendInfo('getInvoiceInfo', $post_json);
        $return ['invoiceInfo'] = array();
        $temp ['invoiceType'] = $data ['data'] ['invoice_type'] == 1 ? 2 : 1;
        $temp ['invoiceNo'] = $data ['data'] ['invoice_duty'];
        $temp ['invoiceMoney'] = $data ['data'] ['invoice_money'];
        if ($data ['data'] ['state'] == 2) {
            $temp ['invoiceUrl'] = $data ['data'] ['invoice_proof'] ['save_path'];
        }
        if ($get_order['invoice_state'] != 2) {
            $this->errorReturn('当前发票状态不能上传');
        }
        if (!strstr($temp['invoiceUrl'], 'https://tailongji.dixintong.com')) {
            $this->errorReturn('发票地址错误');
        }
        array_push($return ['invoiceInfo'], $temp);
        $this->successReturn($return);
    }

    // 物流查询
    public function getOrderLogistics()
    {
        $orderdb = new Orderdb ();
        $order_no = $this->request ['tradeNo'];
        $orderdb->param ['out_order_no'] = $order_no;
        $get_order = $orderdb->ajaxOrderNo();
        $return ['sendState'] = $get_order ['shopping_state'] == 1 ? 1 : 2;
        $return ['logisticsInfo'] = array();
        $memberdb = new Memberdb();
        $set_member_id = $get_order['supplier_er'] ? $get_order['supplier_er'] : $get_order['supplier_id'];
        $get_member = $memberdb->where('member_id', $set_member_id)->find();
        $get_name = $get_member['order_member'] ?? '';
        $get_phone = $get_member['order_phone'] ?? '';
        if ($get_order ['shopping_state'] > 1) {
            $temp ['operateInfo'] = "订单已生成【" . $get_name . "," . $get_phone . "】";
            $temp ['operateTime'] = $get_order ['create_time'];
            array_push($return ['logisticsInfo'], $temp);
        }
        if ($get_order ['receipt_state'] == 2) {
            $return ['sendState'] = 3;
            $temp ['operateInfo'] = '已妥投';
            $temp ['operateTime'] = $get_order ['receipt_time'];
            array_push($return ['logisticsInfo'], $temp);
        }
        $this->successReturn($return);
    }

    // 申请售后
    public function applyAfterSale()
    {
        $returneddb = new Returneddb();

        foreach ($this->request['products'] as $key => $val) {
            $save_data['order_no'] = 'CS' . $this->request['tradeNo'];
            $save_data['returned_type'] = $this->request['afterSaletype'];
            $save_data['returned_reason'] = $this->request['remark'];
            $save_data['api_param'] = json_encode($this->request);
            $save_data['out_apply_id'] = $this->request['afterSaleID'];
            $save_data['goods_sku'] = $val['sku'];
            $save_data['returned_num'] = $val['number'];
            $returneddb->save($save_data);
        }

        // 处理购物车信息
        $cartdb = new Cartdb();
        $get_cart = $cartdb->where('order_no', $save_data['order_no'])->select();
        foreach ($get_cart as $key => $val) {
            foreach ($this->request['products'] as $k => $v) {
                if ($val['goods_sku'] == $v['sku']) {
                    $cartdb->update(['returned_state' => 2], ['cart_id' => $val['cart_id']]);
                }
            }
        }
        $return = [];
        $this->successReturn($return);
    }

    // 售后完成
    public function completeAfterSale()
    {
        $returneddb = new Returneddb();
        $get_returned = $returneddb->where('order_no', 'CS' . $this->request['tradeNo'])->where('out_apply_id', $this->request['afterSaleID'])->find();
        if ($get_returned) {
            $get_returned->save(['returned_state' => 2]);
        }
        $return = [];
        $this->successReturn($return);
    }

    // 6.5.6 申请订单废止
    public function applyStopOrder()
    {
        $get_data = $this->request;
        $out_order_no = $get_data['tradeNo'];
        $reason = $get_data['reason'];
        $files = $get_data['files'];
        $post_type = $get_data['post_type'] ?? 0;
        $orderdb = new Orderdb();
        $get_order = $orderdb->where('out_order_no', $out_order_no)->find();
        $return['reason'] = $reason;
        $return['files'] = $files;
        $return['is_feizhi'] = $post_type == 0 ? 4 : 3;
        $get_order->save($return);
        // 写日志
        $log_data['order_no'] = $get_order['order_no'];
        $log_data['member_id'] = MEMBER_ID;
        $log_data['view_text'] = '申请订单废止';
        $log_data['post_json'] = $get_data;
        $log_data['type_index'] = 0;
        $orderLogdb = new OrderLogdb();
        $orderLogdb->save($log_data);

        // 军采提交的
        $this->successReturn([]);
    }

    // 6.5.7 验证审核订单状态
    public function isStopOrder()
    {
        $get_data = $this->request;
        $out_order_no = $get_data['tradeNo'];
        $isStop = $get_data['isStop'];
        $opinion = $get_data['opinion'];
        $post_type = $get_data['post_type'] ?? 0;
        $orderdb = new Orderdb();
        $get_order = $orderdb->where('out_order_no', $out_order_no)->find();
        $return['opinion'] = $opinion;
        $return['is_feizhi'] = $isStop == 1 ? 1 : 2;
        if ($isStop == 1) {
            $return['order_state'] = -1;
            $return['cancel_time'] = time();
            $return['cancel_type'] = 2;
        }
        $get_order->save($return);
        // 写日志
        $log_data['order_no'] = $get_order['order_no'];
        $log_data['member_id'] = MEMBER_ID;
        $log_data['view_text'] = '审核终止订单';
        $log_data['post_json'] = $get_data;
        $log_data['type_index'] = 0;
        $orderLogdb = new OrderLogdb();
        $orderLogdb->save($log_data);
        $return['tradeNo'] = $get_order['out_order_no'];
        $return['isStop'] = $return['is_feizhi'];
        // 军采提交的
        $this->successReturn([]);
    }
}